package puyu.manage.service.utils;


import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import puyu.manage.service.utils.except.BaseException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.Method;

import java.util.*;


import java.net.HttpURLConnection;
import java.net.URL;

/**
 *  @ClassName: 公共方法
 *  @author: whl
 *  @Date: 2024/5/28 20:44
 *  @Description: Description of this class
 */

public class CommonUtil {


    /**
     * 获得日期，yyyyMMdd格式.
     *
     * @param timestampstr yyyyMMddHHmmssSSS格式字符串
     * @return yyyyMMdd格式字符串
     */
    public static String getCreateDate(String timestampstr) {
        return timestampstr.substring(0, 8);
    }


    /**
     * 解析字符串，空值或空字符串返回null.
     *
     * @return 字符串
     */
    public static String parseString(Object obj) {
        if (obj == null || "".equals(obj) || "null".equals(obj)) {
            return null;
        }
        return String.valueOf(obj);
    }

    /**
     * 解析布尔值.
     *
     * @return 布尔值
     */
    public static boolean parseBoolean(Object obj) {
        if (obj == null) {
            return false;
        }
        return String.valueOf(obj).equals("true");
    }


    /**
     * 将过长的in语句解析成or语句
     *
     * @return or和in语句
     */
    public static String parseInSql(String colcode, String[] guids) {
        return parseInSql(colcode, Arrays.asList(guids));
    }

    /**
     * 将过长的in语句解析成or语句
     *
     * @return or和in语句
     */
    public static String parseInSql(String colcode, Collection<String> guids) {
        StringBuilder vchsql = new StringBuilder("(");
        vchsql.append(colcode).append(" in( ");
        int index = 0;
        Iterator iterator = guids.iterator();
        for (; iterator.hasNext(); ) {
            index++;
            vchsql.append("'").append(iterator.next()).append("'");
            if (iterator.hasNext()) {
                if (index == 998) {
                    index = 0;
                    vchsql.append(") or ").append(colcode).append(" in (");
                } else {

                    vchsql.append(",");
                }
            }
        }
        return vchsql.append("))").toString();
    }

    /**
     * 将过长的in语句解析成or语句
     *
     * @return or和in语句
     */
    @SuppressWarnings("rawtypes")
    public static String parseInSql(String colcode, List<? extends Map> dtos, String key) {
        StringBuilder vchsql = new StringBuilder("(");
        vchsql.append(colcode).append(" in( ");
        int index = 0;
        Iterator iterator = dtos.iterator();
        for (; iterator.hasNext(); ) {
            index++;
            Map dto = (Map) iterator.next();
            vchsql.append("'").append(dto.get(key)).append("'");
            if (iterator.hasNext()) {
                if (index == 998) {
                    index = 0;
                    vchsql.append(") or ").append(colcode).append(" in (");
                } else {

                    vchsql.append(",");
                }
            }
        }
        return vchsql.append("))").toString();
    }

    /**
     * 将过长的in语句解析成or语句
     *
     * @return or和in语句
     */
    public static String parseNotInSql(String colcode, String[] guids) {
        return parseNotInSql(colcode, Arrays.asList(guids));
    }

    /**
     * 将过长的in语句解析成or语句
     *
     * @return or和in语句
     */
    public static String parseNotInSql(String colcode, Collection<String> guids) {
        StringBuilder vchsql = new StringBuilder("(");
        vchsql.append(colcode).append(" not in( ");
        int index = 0;
        Iterator iterator = guids.iterator();
        for (; iterator.hasNext(); ) {
            index++;
            vchsql.append("'").append(iterator.next()).append("'");
            if (iterator.hasNext()) {
                if (index == 998) {
                    index = 0;
                    vchsql.append(") and ").append(colcode).append(" not in (");
                } else {

                    vchsql.append(",");
                }
            }
        }
        return vchsql.append("))").toString();
    }


    /**
     * 根据方法名获取方法对象
     *
     * @param c          方法所属的类
     * @param methodName 方法名
     * @return 方法对象
     */
    public static Method getMethod(Class c, String methodName) {
        Method aMethod = null;
        try {
            Method m[] = c.getMethods();
            for (int i = 0; i < m.length; i++) {
                if (m[i].getName().equals(methodName)) {
                    aMethod = m[i];
                    break;
                }
            }
        } catch (SecurityException ex) {
            throw new RuntimeException("方法获取异常");
        }
        return aMethod;
    }

    public static <T> String toString(Collection<T> c, ItoString<T> ts, String sep, boolean isQuote) {
        if (c == null || c.isEmpty())
            return "";

        StringBuilder sb = new StringBuilder();
        for (Iterator<T> iterator = c.iterator(); ; ) {
            T t = iterator.next();

            if (isQuote)
                sb.append("'");

            if (ts == null) {
                sb.append(t.toString());
            } else {

                sb.append(ts.toString(t));
            }
            if (isQuote)
                sb.append("'");

            if (iterator.hasNext()) {

                sb.append(sep);
            } else {
                break;
            }
        }

        return sb.toString();
    }


    public static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        } else if (obj instanceof String && (((String) obj).equals("") || ((String) obj).equals("null"))) {
            return true;
        } else if (obj instanceof List && ((List) obj).size() == 0) {
            return true;
        } else if (obj.getClass().isArray() && ((Object[]) obj).length == 0) {
            return true;
        } else {
            return false;
        }
    }

    public static String createInSql(String columnname, Collection values) {
        boolean isContainOr = false;
        StringBuilder vchsql = new StringBuilder(values.size() * 32 + 100);
        vchsql.append((new StringBuilder(String.valueOf(columnname))).append(" in( ").toString());
        int index = 0;
        int length = 0;
        for (Iterator iterator = values.iterator(); iterator.hasNext(); ) {
            String id = (String) iterator.next();
            index++;
            length++;
            vchsql.append("'").append(id).append("'");
            if (index == 999 && length != values.size()) {
                isContainOr = true;
                index = 0;
                vchsql.append((new StringBuilder(") or ")).append(columnname).append(" in (").toString());
            } else {
                vchsql.append(",");
            }
        }

        String res = vchsql.deleteCharAt(vchsql.length() - 1).append(")").toString();
        if (values.size() == 0) {
            res = columnname + " in ('')";
        }
        if (isContainOr)
            res = (new StringBuilder("( ")).append(res).append(" )").toString();
        return res;
    }

    public static String createInSql(String columnname, String valueStr) {
        String[] valueStrings = valueStr.split(",");
        List values = new ArrayList();
        for (int i = 0; i < valueStrings.length; i++) {
            values.add(valueStrings[i]);
        }
        boolean isContainOr = false;
        StringBuilder vchsql = new StringBuilder(values.size() * 32 + 100);
        vchsql.append((new StringBuilder(String.valueOf(columnname))).append(" in( ").toString());
        int index = 0;
        int length = 0;
        for (Iterator iterator = values.iterator(); iterator.hasNext(); ) {
            String id = (String) iterator.next();
            index++;
            length++;
            vchsql.append("'").append(id).append("'");
            if (index == 999 && length != values.size()) {
                isContainOr = true;
                index = 0;
                vchsql.append((new StringBuilder(") or ")).append(columnname).append(" in (").toString());
            } else {
                vchsql.append(",");
            }
        }

        String res = vchsql.deleteCharAt(vchsql.length() - 1).append(")").toString();
        if (values.size() == 0) {
            res = columnname + " in ('')";
        }
        if (isContainOr)
            res = (new StringBuilder("( ")).append(res).append(" )").toString();
        return res;
    }

    public static Map parseMapKeyUpper(Map map) {
        Map res = new HashMap();
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            res.put(key.toUpperCase(), map.get(key));
        }
        return res;
    }

    public static MultipartFile imageConvert(String imageString) {
        imageString = imageString.substring(imageString.indexOf(",") + 1);
        // Base64编码的图片字符串
        byte[] imageBytes = Base64.getDecoder().decode(imageString);
        // 指定文件名和类型
        String fileName = "image.jpg"; // 根据实际情况指定文件名和扩展名
        String contentType = "image/jpeg"; // 根据实际图片类型指定

        // 创建MultipartFile对象
        MultipartFile multipartFile = new MockMultipartFile(fileName, fileName, contentType, imageBytes);
        return multipartFile;
    }


    public static CommonData pdfConvertImage(MultipartFile file) throws IOException{
        File convFile = new File(file.getOriginalFilename());
        convFile.createNewFile();
        try (InputStream in = file.getInputStream();
             OutputStream out = new FileOutputStream(convFile)) {
            byte[] bytes = new byte[1024];
            int read;
            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
        }
        PDDocument document = PDDocument.load(convFile);
        // 创建PDF渲染器
        PDFRenderer pdfRenderer = new PDFRenderer(document);

        // 渲染第一页为图片
        BufferedImage image = pdfRenderer.renderImageWithDPI(0, 300, ImageType.RGB);
        //image = FileUtils.rotateImage(image,"right"); // 向右旋转90度

        //判断图片是横板的还是竖版的，1横板 2竖版
        int width = image.getWidth();
        int height = image.getHeight();

        String direction;
        if (width > height) {
            direction = "1"; // 横板
        } else {
            direction = "2"; // 竖版
        }

        // 保存图片到文件
        File outputFile = new File(String.valueOf(file));
        ImageIO.write(image, "jpg", outputFile);


        FileInputStream input = new FileInputStream(outputFile);
        byte[] fileBytes = IOUtils.toByteArray(input);

        MultipartFile multipartFile = new MockMultipartFile("file", file.getName() + ".jpg", "image/jpeg", fileBytes);

        CommonData data = new CommonData();
        data.setFile(multipartFile);
        data.setDirection(direction);

        return data;
    }


    public static MultipartFile videoConvert(String videoString) {
        File file = new File(videoString);

        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("file", "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(file);
            os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            throw new BaseException("读取文件失败");
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != fis) {
                    fis.close();
                }
            } catch (Exception e) {
                throw new BaseException("关闭文件失败");
            }

        }

        MultipartFile mfile = null;
        if (item != null) {
            mfile = new CommonsMultipartFile(item);
        }

        return mfile;

    }


    public static MultipartFile downloadFileAsMultipart(String videoUrl) throws IOException {
        // Step 1: Download the file from the URL
        URL url = new URL(videoUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        InputStream inputStream = connection.getInputStream();

        // Step 2: Convert the downloaded file to MultipartFile
        byte[] fileBytes = IOUtils.toByteArray(inputStream);
        MultipartFile multipartFile = new MockMultipartFile("file", "video.mp4", "video/mp4", fileBytes);

        // Close the InputStream
        inputStream.close();

        return multipartFile;

    }


}
